package com.yexx.starter.optms.logger.filter;

import com.yexx.starter.optms.logger.contexts.GlobalContextHolder;
import com.yexx.starter.optms.logger.properties.TraceProperties;
import com.yexx.starter.optms.logger.utils.ParseTraceUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * Description: 追踪过滤器
 *
 * @author zuomin (myleszelic@outlook.com)
 * @date: 2022/06/26-20:03
 */
@Slf4j
public class TraceFilter extends OncePerRequestFilter {

    private final TraceProperties traceProperties;

    public TraceFilter(TraceProperties traceProperties) {
        this.traceProperties = traceProperties;
    }

    @Override
    protected boolean shouldNotFilter(HttpServletRequest request) {
        return !traceProperties.enable();
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        try {
            ParseTraceUtils.putMDC(request);
            ParseTraceUtils.parseHeader(request, traceProperties.getHeaders());
            ParseTraceUtils.parseParam(request, traceProperties.getParams());
            ParseTraceUtils.parseContext(traceProperties.getContexts());

            filterChain.doFilter(request, response);
        } finally {
            ParseTraceUtils.removeDMC();
            GlobalContextHolder.clear();
        }
    }
}
